In [1]:
a = 5
name = "Shantnu"
print(a)
print(name)
In [2]:
names = ["Shantnu", "John", "Sally"]
print(names)
In [3]:
for name in names:
print("Hello ", name)
In [14]:
names.append("Mr Smith")
print(names)
In [5]:
# Ipython only! be careful
names
Out[5]:
In [7]:
# Start from 0
print(names[0])
print(names[2])
In [9]:
# Weird!
print(names[-1])
# prints last value
print(names[-2])
In [11]:
# learn to google! Remove from list
names.append("Wrong name! Please remove me")
print(names)
In [13]:
del names[-1]
print(names)
In [15]:
names
Out[15]:
In [17]:
# Array slicing
# Add another few names. Make it 10
names.append("K")
names.append("l")
names.append("m")
names.append("n")
names
Out[17]:
In [18]:
# prnt 1st five names
names[:5]
Out[18]:
In [19]:
names[5:]
Out[19]:
In [20]:
# And this is where it gets interetsing
names[2:6]
Out[20]:
In [26]:
# You can even do
# removes 1st and last valyues!
names[1:-1]
Out[26]:
In [27]:
# Go from 2 to 6 in steps of 2
names[2:6:2]
Out[27]:
In [37]:
# If loop
for name in names:
if (name == "Sally"):
print("Found Sally!")
elif (name == "l"):
print("Mr T found")
else:
print("Unknown name")
In [28]:
age_dict = {"Bob":21, "Sally":33, "L":2}
age_dict
Out[28]:
In [29]:
age_dict["Bob"]
Out[29]:
In [30]:
age_dict["Shantnu"] = 16
age_dict
Out[30]:
In [34]:
# We have a list. Divide each value by 5
numbers = [5,10,15,20,25]
numbers2 = []
for n in numbers:
numbers2.append(n / 5)
print(numbers)
print(numbers2)
In [35]:
numbers3 = [ n / 5 for n in numbers]
print(numbers3)
In [36]:
import numpy as np
numbers_np = np.array(numbers)
numbers_np = numbers_np / 5
print(numbers_np)
In [39]:
# Strings are like lists!
name = "Shantnu"
for n in name:
print(n)
In [40]:
sirname = "Tiwari"
print(name + sirname)
In [42]:
with open("names.txt", "r") as f:
names_file = f.read()
print(names_file)
In [44]:
names_file_separate = names_file.split(",")
names_file_separate
Out[44]:
In [54]:
names_file_separate = [name.replace(" ", "") for name in names_file_separate]
names_file_separate
Out[54]:
In [55]:
def hello(name):
print("Hello ", name)
hello("Shantnu")
In [56]:
def hello2(name):
return "Hello " + name
print(hello2("Shantnu") )
In [57]:
def hello_age(name, age):
name_hello = "Hello " + name
age = age + 10
return name_hello, age
name_hello, age = hello_age("Shan", 16)
print("Hello {} in 10 years you will be {} years old! Shocking".format(name_hello, age ))
In [ ]: